<template>
  <div class="products-container">
    <div class="header">
      <h3>农产品管理</h3>
      <el-button type="primary" @click="handleAdd">上架农产品</el-button>
    </div>

    <el-table :data="productList" v-loading="loading">
      <el-table-column label="商品图片" width="120">
        <template #default="scope">
          <el-image
            :src="scope.row.avatar"
            :preview-src-list="[scope.row.avatar]"
            fit="cover"
            class="product-image"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="name" />
      <el-table-column label="商品描述" prop="description" />
      <el-table-column label="价格" prop="price" width="100" />
      <el-table-column label="商品类型" prop="productType" width="120" />
      <el-table-column label="销量" prop="salesVolume" width="100" />
      <el-table-column label="生产日期" prop="productionDate" width="180" />
      <el-table-column label="过期日期" prop="expirationDate" width="180" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button link type="danger" @click="handleOffShelf(scope.row)"
            >下架</el-button
          >
        </template>
      </el-table-column>

      <!-- 自定义空数据显示 -->
      <template #empty>
        <el-empty description="还没有上架农产品" :image-size="200">
          <el-button type="primary" @click="handleAdd">立即上架</el-button>
        </el-empty>
      </template>
    </el-table>

    <!-- 添加农产品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑农产品' : '上架农产品'"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入商品描述"
          />
        </el-form-item>

        <el-form-item label="商品类型" prop="productType">
          <el-select v-model="form.productType" placeholder="请选择商品类型">
            <el-option label="果蔬" :value="1" />
            <el-option label="畜产" :value="2" />
            <el-option label="水产" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="form.price"
            :precision="2"
            :step="0.1"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker
            v-model="form.productionDate"
            type="date"
            placeholder="选择生产日期"
          />
        </el-form-item>

        <el-form-item label="过期日期" prop="expirationDate">
          <el-date-picker
            v-model="form.expirationDate"
            type="date"
            placeholder="选择过期日期"
          />
        </el-form-item>

        <el-form-item label="商品图片" prop="avatar">
          <input
            type="file"
            accept="image/jpeg,image/png"
            @change="handleFileChange"
            style="display: none"
            ref="fileInput"
          />
          <div @click="triggerFileInput" style="cursor: pointer">
            <img v-if="form.avatar" :src="form.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import request from "@/utils/request"; // 使用默认导入
import type { AxiosResponse } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Picture } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";

interface Product {
  id: number;
  name: string;
  description: string;
  avatar: string;
  productType: number;
  price: number;
  salesVolume: number;
  productionDate: string;
  expirationDate: string;
  isDeleted: number;
}

const productList = ref<Product[]>([]);

const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const uploadUrl = "/api/file/ali/upload";

const form = ref({
  id: 0,
  name: "",
  description: "",
  productType: "",
  price: 0,
  productionDate: "",
  expirationDate: "",
  avatar: "",
});

const rules = {
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  description: [{ required: true, message: "请输入商品描述", trigger: "blur" }],
  productType: [
    { required: true, message: "请选择商品类型", trigger: "change" },
  ],
  price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
  productionDate: [
    { required: true, message: "请选择生产日期", trigger: "change" },
  ],
  expirationDate: [
    { required: true, message: "请选择过期日期", trigger: "change" },
  ],
  avatar: [{ required: true, message: "请上传商品图片", trigger: "change" }],
};

const fileInput = ref<HTMLInputElement | null>(null);

// 添加编辑状态标记
const isEdit = ref(false);

const loading = ref(false);

const typeMap: Record<number, string> = {
  1: "水果",
  2: "蔬菜",
  3: "其他",
};

// 格式化商品类型
const formatProductType = (type: number) => {
  const typeMap: Record<number, string> = {
    1: "果蔬",
    2: "畜产",
    3: "水产",
  };
  return typeMap[type] || "未知";
};

// 格式化日期
const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString();
};

const getProductList = async () => {
  try {
    const res = await request({
      url: "/agriculturalProduct/queryRuralProd",
      method: "get",
    });
    if (res.success) {
      productList.value = res.data;
    }
  } catch (error) {
    ElMessage.error("获取商品列表失败");
  }
};

// 打开添加对话框
const handleAdd = () => {
  isEdit.value = false;
  dialogVisible.value = true;
  // 重置表单数据
  form.value = {
    id: 0,
    name: "",
    description: "",
    productType: "",
    price: 0,
    productionDate: "",
    expirationDate: "",
    avatar: "",
  };
  // 重置表单校验结果
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 打开编辑对话框
const handleEdit = (row: any) => {
  isEdit.value = true;
  dialogVisible.value = true;
  // 填充表单数据
  form.value = {
    id: row.id,
    name: row.name,
    description: row.description,
    productType: row.productType,
    price: row.price,
    productionDate: row.productionDate,
    expirationDate: row.expirationDate,
    avatar: row.avatar,
  };
};

// 下架商品
const handleOffShelf = (row: any) => {
  ElMessageBox.confirm("确定要下架该商品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await request({
          url: "/agriculturalProduct/down",
          method: "post",
          data: {
            id: row.id,
          },
        });

        if (res.success) {
          ElMessage.success("商品下架成功");
          // 刷新列表
          getProductList();
        }
      } catch (error) {
        ElMessage.error("商品下架失败");
      }
    })
    .catch(() => {
      // 取消下架操作，不做任何处理
    });
};

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click();
};

// 处理文件选择
const handleFileChange = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  const file = input.files?.[0];

  if (file) {
    // 验证文件
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJpgOrPng) {
      ElMessage.error("图片只能是 JPG 或 PNG 格式!");
      return;
    }
    if (!isLt2M) {
      ElMessage.error("图片大小不能超过 2MB!");
      return;
    }

    // 创建 FormData
    const formData = new FormData();
    formData.append("uploadFile", file);

    try {
      const res = await request({
        url: "/file/ali/upload",
        method: "post",
        data: formData,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });

      if (res.success) {
        form.value.avatar = res.data;
        ElMessage.success("图片上传成功");
      }
    } catch (error) {
      ElMessage.error("图片上传失败");
    }
  }

  // 清空文件选择，允许选择相同文件
  input.value = "";
};

// 修改 submitForm 方法
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 格式化日期
        const formatDate = (date: Date) => {
          return date
            .toLocaleString("zh", {
              year: "numeric",
              month: "2-digit",
              day: "2-digit",
              hour: "2-digit",
              minute: "2-digit",
              second: "2-digit",
            })
            .replace(/\//g, "-");
        };

        // 构造请求数据
        const submitData = {
          id: form.value.id, // 编辑时需要传id
          name: form.value.name,
          description: form.value.description,
          productType: Number(form.value.productType),
          price: Number(form.value.price),
          productionDate: formatDate(new Date(form.value.productionDate)),
          expirationDate: formatDate(new Date(form.value.expirationDate)),
          avatar: form.value.avatar,
        };

        // 根据是否是编辑模式选择不同的接口
        const url = isEdit.value
          ? "/agriculturalProduct/updateInfo"
          : "/agriculturalProduct/add";

        const res = await request({
          url,
          method: "post",
          data: submitData,
        });

        if (res.success) {
          ElMessage.success(isEdit.value ? "商品修改成功" : "商品上架成功");
          dialogVisible.value = false;
          getProductList(); // 刷新列表
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? "商品修改失败" : "商品上架失败");
      }
    }
  });
};

onMounted(() => {
  getProductList();
});
</script>

<style lang="scss" scoped>
.products-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      color: #303133;
    }
  }

  .product-image {
    width: 80px;
    height: 80px;
    border-radius: 4px;
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
  }

  :deep(.el-empty) {
    padding: 40px 0;

    .el-empty__description {
      margin-top: 20px;
      font-size: 14px;
      color: #909399;
    }

    .el-button {
      margin-top: 20px;
    }
  }

  .avatar {
    width: 100px;
    height: 100px;
    border-radius: 4px;
    object-fit: cover;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style> 